<?php
namespace app\home\controller;
class Fos extends Common{
	
    public function _initialize(){
        parent::_initialize();
		$user = db('users')->where('id', session('home_uid'))->find();
		$this->assign('user', $user);
    }

    public function index(){  	
        return $this->fetch();
    }
	
	public function trade_list(){
		$rows = db('shop')->order('sort')->select();
		$this->assign("shop", $rows);
		$this->assign("count", input('param.count'));
		return $this->fetch();
	}
	
	
	public function go_pay(){
		$count = input('param.count');
		$shop = db('shop')->where('id', input('param.shop_id'))->find();
		$this->assign('shop', $shop);
		$this->assign('amount', number_format(round($count*2000, 2), 2));
		$this->assign('count', $count);
		
		$this->assign('code', rand(100000, 999999));
		return $this->fetch();
	}
	
	public function httpGet($pUrl){
		$tCh = curl_init();
		curl_setopt($tCh, CURLOPT_URL, $pUrl);
		curl_setopt($tCh, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($tCh, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($tCh, CURLOPT_TIMEOUT, 1);
		$tResult = curl_exec($tCh);
		if (curl_errno($tCh)) {
			echo 'Curl error: ' . curl_error($tCh);
		}
		curl_close($tCh);
		$tResult=json_decode ($tResult,true);
		return $tResult;
	}
	
	public function pay(){
		$pay_type = input('param.pay_type');
		$count = input('param.count');
		$shop_id = input('param.shop_id');
		$code = input('param.code');
		
		$url = "http://api.zb.cn/data/v1/ticker?market=eth_qc";
		$tmp = $this->httpGet($url);
		
		$this->assign('count', $count);
		$this->assign('amount', number_format(round($count*2000, 2), 2));
		$this->assign('val', number_format($count*2000/6.974/$tmp['ticker']['last'],8));
		$this->assign('real_amount', round($count*2000, 2));
		
		$this->assign("pay_type", $pay_type);
		$this->assign("code", $code);
		//支付方式
		$shop = db('shop')->where('id', input('param.shop_id'))->find();
		$this->assign('shop', $shop);
		
		//TODO:可以购买count数量?
		
		return $this->fetch();
	}
	
	public function comfirm_pay(){
		$map['shop_id'] = input('param.shop_id');
		$map['count'] = input('param.count');
		$map['code'] = input('param.code');
		$map['pay_type'] = input('param.pay_type');
		$map['m_id'] = session("home_uid");
		$map['add_time'] = date("Y-m-d H:i:s");
		if(db('buy_list')->insert($map)){
			echo 1;
		}else{
			echo -1;
		}
	}

    public function subscrible(){  
	    //认证提示语
	    $system = db('system')->field('buy_tips')->find(1);
	    $level = db('users')->where('id', session('home_uid'))->value("level");
	    $limit_amount = db('rule')->where("level", "F".$level)->value("amount");
		$this->assign("limit_amount", $limit_amount);
		$this->assign("buy_tips", $system['buy_tips']);
		$user = db('users')->where('id', session('home_uid'))->find();
		//$this->assign("amount", intval($user['coin'])+intval($user['freeze_fos']));
		
		//TODO:handle process
		$count = db('buy_list')->where("m_id", session('home_uid'))->where('status', 0)->count();
		$this->assign('count', $count);
		
		$fos_count = db('buy_list')->where(['m_id'=>session('home_uid'), 'status'=>2])->sum("count");
		$this->assign("amount", $fos_count);
        return $this->fetch();
    }
	
	public function my_team()
    {  	
	    $l1_list = db("users")->where('parent_id', session("home_uid"))->select();
		$l1_ids = [];
		foreach($l1_list as $itm){$l1_ids[] = $itm['id'];};
		if($l1_ids){
			$l2_list = db("users")->where('parent_id IN('.implode(",", $l1_ids).')')->select();
			foreach($l2_list as $itm){$l2_ids[] = $itm['id'];};
		    if($l2_ids){
			    $l3_list = db("users")->where('parent_id IN('.implode(",", $l2_ids).')')->select();
			}
		}
		$c = count($l1_list)+count($l2_list)+count($l3_list);
		$this->assign('t_count', $c);
    	return $this->fetch();
    }
	
	public function code()
    {  	
    	return $this->fetch();
    }
	
	public function distribution(){  	
	    $rows = db('log')->where('m_id', session('home_uid'))->where('type', 3)->select();
		$this->assign('rows', $rows);
    	return $this->fetch();
    }
	
	public function team()
    {  	
	    $l1_list = db("users")->where('parent_id', session("home_uid"))->select();
		
		$l1_ids = [];
		foreach($l1_list as $itm){$l1_ids[] = $itm['id'];};
		if($l1_ids){
			$l2_list = db("users")->where('parent_id IN('.implode(",", $l1_ids).')')->select();
			foreach($l2_list as $itm){$l2_ids[] = $itm['id'];};
		    if($l2_ids){
			    $l3_list = db("users")->where('parent_id IN('.implode(",", $l2_ids).')')->select();
			}
		}
		$c = count($l1_list)+count($l2_list)+count($l3_list);
		$this->assign('t_count', $c);
		$this->assign('l1_list', $l1_list);
		$this->assign('l2_list', $l2_list);
		$this->assign('l3_list', $l3_list);
    	return $this->fetch();
    }
	
	public function challenge(){  	
    	return $this->fetch();
    }

	public function c_info()
    {  	
    	return $this->fetch();
    }
	
	//=======================方法====================
	public function buy_fos(){
		$count = intval(input("param.count"));
		//会员限制购买多少个
		$user = db('users')->where('id', session('home_uid'))->find();
		$limit_amount = db('rule')->where("level", "F".$user['level'])->value("amount");
		$data = ["error"=>0, "msg"=>'认购成功!'];
		if(($user.coin+$count)>$limit_amount){
			$data['error'] = 1;
			$data['msg'] = "超过限额(".$limit_amount."枚)";
		}else{
			//判断零钱包钱是否足够
			$fos_price = db('config')->where("name", "fos_price")->value("value");
			$need_amount = $fos_price*$count;
			if($user['money'] < $need_amount){
				$data['error'] = 1;
				$data['msg'] = "余额不足!";
				$data['url'] = url('Mcenter/recharge');
			}else{
				$map['money'] = $user['money'] - $need_amount;
				$map['coin'] = $user['coin'] + $count;
				$map['is_buy'] = 1;
				$ret = db('users')->where('id', session('home_uid'))->update($map);
				if(!$ret){
					$data['error'] = 1;
					$data['msg'] = "系统繁忙，请稍后重试!";
				}else{
					//用户是初次升至F1,则计算上级和上上级是否升级
					if($user['is_buy'] == 0){
					    $this->cal_m_level();
					}
				}
				//记录log
				$this->add_log(session('home_uid'), $need_amount, "购买FOS(".$count.")", 1, $user['money'], $map['money']);
			}
		}
		echo json_encode($data);
	}
	
	
	public function cal_m_level(){
		/*-------上级---------*/
		$pid = db("users")->where("id", session("home_uid"))->value("parent_id");
		if($pid){
			//规则
			$rule = db("upgrade")->order("id ASC")->select();
			//获取1-3级F1的数量
			$p_info = db('users')->where("id", $pid)->find();
			$l1_list = db('users')->where(["parent_id"=>$pid, 'level'=>1])->select();
			$l1_pids = [];
			foreach($l1_list as $itm){$l1_pids[] = $itm['id'];};
			$l2_list = db('users')->where("parent_id IN (".implode(",", $l1_pids).") AND level=1]")->select();
			$l2_pids = [];
			foreach($l2_list as $itm){$l2_pids[] = $itm['id'];};
			$l3_list = db('users')->where("parent_id IN (".implode(",", $l2_pids).") AND level=1]")->select();
			//判断是否升级
			$new_lev = $p_info['level'];
			foreach($rule as $itm){
				if(count($l1_list) >= $itm['lev_1_count'] && count($l2_list) >= $itm['lev_2_count'] &&count($l3_list) >= $itm['lev_3_count']){
					$new_lev = $itm['id'];
				}
			}
			if($new_lev > $p_info['level']){
				//更新上级级别
				db("users")->where("id", $pid)->update(["level"=>$new_lev]); 
			}
			
			/*-------上上级---------*/
			$ppid = $pid = db("users")->where("id", $pid)->value("parent_id");
			if($ppid){
				$pp_info = db('users')->where("id", $ppid)->find();
				$l1_list = db('users')->where(["parent_id"=>$ppid, 'level'=>1])->select();
				$l1_pids = [];
				foreach($l1_list as $itm){$l1_pids[] = $itm['id'];};
				$l2_list = db('users')->where("parent_id IN (".implode(",", $l1_pids).") AND level=1]")->select();
				$l2_pids = [];
				foreach($l2_list as $itm){$l2_pids[] = $itm['id'];};
				$l3_list = db('users')->where("parent_id IN (".implode(",", $l2_pids).") AND level=1]")->select();
				//判断是否升级
				$new_lev = $pp_info['level'];
				foreach($rule as $itm){
					if(count($l1_list) >= $itm['lev_1_count'] && count($l2_list) >= $itm['lev_2_count'] &&count($l3_list) >= $itm['lev_3_count']){
						$new_lev = $itm['id'];
					}
				}
				if($new_lev > $pp_info['level']){
					//更新上级级别
					db("users")->where("id", $ppid)->update(["level"=>$new_lev]); 
				}
			}
		}		
	}
}